import React, { useState } from "react";
import { Form, Input, Button, message } from "antd";
import { Link, useLocation } from "react-router-dom";
import { getEmailCode, login } from "@/api/api";
import { useNavigate } from "react-router-dom";
import "./index.css";

const Login: React.FC = () => {
  const navigation = useNavigate();
  const { Search } = Input;
  const { pathname } = useLocation();
  const [loadingType, setLoadingType] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  let type = {
    loginType: "password",
    pathname: "/loginEmail",
    text: "邮箱验证码登录",
  };
  if (pathname === "/loginEmail") {
    type.loginType = "email";
    type.pathname = "/login";
    type.text = "账号密码登录";
  }

  const search = (value: any) => {
    setLoadingType(true);
    getEmailCode(value).then((res) => {
      setLoadingType(false);
      if (res.code === 200) {
        message.success(res.msg);
      } else {
        message.warn(res.msg);
      }
    });
  };
  const finish = (value: any) => {
    setFormLoading(true);
    value.type = type.loginType;
    login(value).then((res) => {
      setFormLoading(false);
      if (res.code === 200) {
        message.success(res.msg);
        localStorage.setItem("token", res.data.token ?? "");
        navigation("/");
      } else {
        message.warn(res.msg);
      }
    });
  };
  return (
    <>
      <div className={""}>
        <Form onFinish={finish} className={"form"} name="login">
          <Form.Item name="user_name">
            {type.loginType === "password" ? (
              <Input placeholder={"你的邮箱"} />
            ) : (
              <Search
                placeholder={"你的邮箱"}
                onSearch={search}
                enterButton={"发送验证码"}
                loading={loadingType}
              />
            )}
          </Form.Item>

          <Form.Item name="user_password">
            <Input.Password placeholder={"你的密码"} />
          </Form.Item>
          <div className={"login-nav"}>
            <Link to={"/forget"}>忘记密码</Link>
            <Link to={type.pathname}>{type.text}</Link>
            <Link to={"/reg"}>注册</Link>
          </div>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={formLoading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </>
  );
};
export default Login;
